<!DOCTYPE HTML>
<html>

	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<meta name="HandheldFriendly" content="true" />
		<meta name="MobileOptimized" content="320" />
		<title>录音</title>

		<link rel="stylesheet" href="../css/commonn.css" type="text/css" charset="utf-8" />
		<link rel="stylesheet" href="../css/mui.min.css" />
		<link rel="stylesheet" href="../css/main.css" />
		<link rel="stylesheet" href="../css/mui.picker.css" />
		<link rel="stylesheet" href="../css/mui.poppicker.css" />
		<link rel="stylesheet" href="../css/feedback.css" />
		<!--图标-->
		<link rel="stylesheet" type="text/css" href="../css/icons-extra.css" />
		<style type="text/css">
			.rp {
				width: 100%;
				height: 100%;
				display: none;
				text-align: center;
				position: fixed;
				top: 0;
				background: rgba(0, 0, 0, 0.8);
				z-index: 9999;
				overflow: hidden;
			}
			
			.aname {
				font-size: 16px;
			}
			
			.ainf {
				font-size: 12px;
			}
			
			.rtime {
				font-size: 22px;
				color: #FF0000;
			}
			
			.ptime {
				margin-top: 40%;
				font-size: 22px;
				color: #FFFFFF;
			}
			
			.rprogress {
				background: url(../img/arecord.png) no-repeat center center;
				background-size: 32px 32px;
			}
			
			.rschedule {
				background-color: rgba(0, 0, 0, 0);
				border: 5px solid rgba(0, 183, 229, 0.9);
				opacity: .9;
				border-left: 5px solid rgba(0, 0, 0, 0);
				border-right: 5px solid rgba(0, 0, 0, 0);
				border-radius: 50px;
				box-shadow: 0 0 15px #2187e7;
				width: 36px;
				height: 36px;
				margin: 0 auto;
				-webkit-animation: spin 1s infinite linear;
				animation: spin 1s infinite linear;
			}
			
			@-webkit-keyframes spin {
				0% {
					-webkit-transform: rotate(0deg);
				}
				100% {
					-webkit-transform: rotate(360deg);
				}
			}
			
			@keyframes spin {
				0% {
					transform: rotate(0deg);
				}
				100% {
					transform: rotate(360deg);
				}
			}
			
			.progress {
				width: 90%;
				background-color: #666;
				margin: 0 5%;
				border: 1px solid #222;
				-webkit-border-radius: 5px;
				border-radius: 5px;
			}
			
			.schedule {
				width: 8px;
				height: 8px;
				margin: 1px 0;
				background-color: #FFCC33;
				-webkit-border-radius: 4px;
				border-radius: 4px;
				-webkit-transition: all 1s linear;
				transition: all 1s linear;
			}
			
			.stop {
				width: 72px;
				height: 72px;
				background: url(../images/mine/tz.png) center center;
				background-size: 72px 72px;
				margin: auto;
				-webkit-border-radius: 72px;
				border-radius: 72px;
			}
			
			.stop:active {
				-webkit-box-shadow: 0 3px 8px rgba(0, 0, 0, 0.5) inset;
				box-shadow: 0 3px 8px rgba(0, 0, 0, 0.5) inset;
			}
			
			.iplay {
				display: block;
				background: no-repeat right center url();
				background-size: 50px 44px;
				-ms-touch-action: auto;
			}
			/*#ptitle {
				font-size: 0.4rem !important;
			}*/
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav" style="padding-top:5%;">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title" id="ptitle" style="">录音</h1>
		</header>
		<div id="dcontent" class="dcontent" style="overflow-y:hidden">
			<div style="position:relative; width: 100%;height: 160px;top: 50px;">
				<div class="button" onclick="startRecord()"><img src="../images/mine/ksly.png" style="width:35%" alt="" /></div>
			</div>
			<div style="position:relative; width: 100%;height: 100%;top: 70px;padding-bottom:250px;overflow-y:auto" >
				<ul id="history" class="dlist" style="text-align:left;">
					<li id="empty" class="ditem-empty">无历史记录</li>
				</ul>
			</div>
			<!--<div class="button button-waring" onclick="cleanHistory()" style="display:none;">清空历史记录</div>-->
		</div>
		<div id="output">
			Audio用于管理音频设备，可调用麦克风录制音频文件，也可播放音频文件。
		</div>
		<div id="play" class="rp">
			<div id="ptime" class="ptime">00:00:00/00:00:00</div><br/>
			<div id="progress" class="progress">
				<div id="schedule" class="schedule"></div>
			</div>
			<br/>
			<div class="stop" onclick="stopPlay(),outSet('停止播放！')"></div>
		</div>
		<div id="record" class="rp">
			<div style="width:100%;height:20%;"></div>
			<div class="rprogress">
				<div class="rschedule"></div>
			</div>
			<br/>
			<div id="rtime" class="rtime">00:00:00</div><br/>
			<div class="stop" onclick="stopRecord()"></div>
		</div>
	</body>
	<script type="text/javascript" src="../js/mui.min.js"></script>
	<script type="text/javascript" src="../js/xiangyingshi.js"></script>
	<script type="text/javascript" src="../js/app.js"></script>
	<script type="text/javascript" src="../js/constants.js"></script>
	<script type="text/javascript" src="../js/sharemethods.js"></script>
	<script type="text/javascript" src="../js/jquery-3.1.1.min.js"></script>
	<script type="text/javascript" src="../js/h5/immersed.js"></script>
	<script type="text/javascript" src="../js/h5/common.js"></script>
	<script type="text/javascript" src="../js/spark-md5.js"></script>
	<script type="text/javascript">
		var gentry = null,
			hl = null,
			le = null;
		var er = null,
			ep = null;
		var bUpdated = false; //用于兼容可能提前注入导致DOM未解析完更新的问题
		// H5 plus事件处理
		var serviceNumber;
		var orderId;
		var pathUrl;

		function removeByValue(arr, val) {
			for(var i = 0; i < arr.length; i++) {
				if(arr[i] == val) {
					console.log(val)
					arr.splice(i, 1);
					break;
				}
			}
		}

		function plusReady() {
			var topoffset = '45px';
			if(plus.navigator.isImmersedStatusbar()) { // 兼容immersed状态栏模式
				// 获取状态栏高度并根据业务需求处理，这里重新计算了子窗口的偏移位置
				topoffset = (Math.round(plus.navigator.getStatusbarHeight()) + 45) + 'px';
				document.querySelector("header").style.height = topoffset;
				document.querySelector("header").style.paddingTop = "20px";
			}
			// 加载完毕后关闭等待框，并展示页面
			var currentView = plus.webview.currentWebview();
			currentView.show('slide-in-right', 200);
			plus.nativeUI.closeWaiting();

			serviceNumber = currentView.serviceNumber;
			console.log(serviceNumber)
			orderId = currentView.orderId;

			var user = localStorage.getItem("USER");
			var user = JSON.parse(user);
			pathUrl = orderId + '/' + serviceNumber + '/';
			// 获取音频目录对象
			plus.io.resolveLocalFileSystemURL('_doc/' + pathUrl, function(entry) {
				entry.getDirectory('audio', {
					create: true
				}, function(dir) {
					gentry = dir;
					updateHistory();
				}, function(e) {
					outSet('Get directory "audio" failed: ' + e.message);
				});
			}, function(e) {
				outSet('Resolve "_doc/" failed: ' + e.message);
			});
		}
		if(window.plus) {
			plusReady();
		} else {
			document.addEventListener('plusready', plusReady, false);
		}
		// DOMContentLoaded事件处理
		document.addEventListener('DOMContentLoaded', function() {
			// 获取DOM元素对象
			hl = document.getElementById('history');
			le = document.getElementById('empty');
			er = document.getElementById('record');
			rt = document.getElementById('rtime');
			ep = document.getElementById('play');
			pt = document.getElementById('ptime');
			pp = document.getElementById('progress')
			ps = document.getElementById('schedule');
			updateHistory();
		}, false);

		var upload = null;
		var getFileMd5 = null;
		mui.plusReady(function() {
			upload = function(filepath, md5, nameStr) {
				var url = serverAddress + uploadfileUrl; //
				var filepath = filepath;
				if(url && filepath) {
					var task = plus.uploader.createUpload(url, {
							method: "POST",
							blocksize: 204800,
							priority: 100
						},
						function(t, status) {
							if(status == 200) {
								var record = JSON.parse(localStorage.getItem("RECORD"));
								removeByValue(record, nameStr);
								console.log(JSON.stringify(record))
							}
						}
					);
					task.addFile(filepath, {
						key: 'single-file'
					});
					task.addData('md5', md5);
					task.addData('orderId', orderId);
					task.addData('serviceNumber', serviceNumber + "");
					var soundLog = JSON.stringify({
						startTime: '',
						endTime: ''
					})
					task.addData('soundLog', soundLog);
					task.start();
				}

			}

			getFileMd5 = function(filePath, nameStr) {
				plus.io.resolveLocalFileSystemURL(filePath, function(entry) {
					var fileReader = new plus.io.FileReader();
					fileReader.readAsDataURL(entry);
					fileReader.onloadend = function(evt) {
						var format = "file";
						//抽取DataURL中的数据部分，从Base64格式转换为二进制格式
						var bin = atob(evt.target.result.split(',')[1]);
						//创建空的Uint8Array
						var buffer = new Uint8Array(bin.length);
						//将图像数据逐字节放入Uint8Array中
						for(var i = 0; i < bin.length; i++) {
							buffer[i] = bin.charCodeAt(i);
						};
						//利用Uint8Array创建Blob对象
						blob = new Blob([buffer.buffer], {
							type: format
						});
						var fileReader1 = new FileReader();
						fileReader1.readAsBinaryString(blob);
						fileReader1.onload = function(evt) {
							if(evt.target.readyState == FileReader.DONE) {
								var imgblob = evt.target.result;
								var sparkMD5 = new SparkMD5();
								sparkMD5.appendBinary(imgblob);
								var MD5 = sparkMD5.end();
								upload(filePath, MD5, nameStr)
							}
						};
					}
				}, function(e) {
					console.log("Resolve file URL failed: " + e.message);
				});
			}
		});

		// 添加播放项
		function createItem(entry) {
			hl = document.getElementById('history');
			le = document.getElementById('empty');
			var li = document.createElement('li');
			li.className = 'ditem';
			li.innerHTML = '<span class="iplay"><font class="aname"></font><br/><font class="ainf"></font></span>';
			li.setAttribute('onclick', 'playAudio(this)');
			hl.insertBefore(li, le.nextSibling);
			li.querySelector('.aname').innerText = entry.name;
			li.querySelector('.ainf').innerText = '...';
			li.entry = entry;
			updateInformation(li);
			// 设置空项不可见
			le.style.display = 'none';
		}
		// 开始录音
		var r = null,
			t = 0,
			ri = null,
			rt = null;

		function startRecord() {
			outSet('开始录音：');
			r = plus.audio.getRecorder();
			if(r == null) {
				outLine('录音对象未获取');
				return;
			}
			r.record({
				filename: '_doc/' + pathUrl + 'audio/'
			}, function(p) {
				outLine('录音完成：' + p);
				plus.io.resolveLocalFileSystemURL(p, function(entry) {
					var os = 'U_' + orderId + '_' + serviceNumber + '_'
					console.log(os)
					var record = localStorage.getItem("RECORD");
					if(!record) {
						record = [];
					} else {
						record = JSON.parse(record)
					}
					record.push(os + entry.name)
					localStorage.setItem('RECORD', JSON.stringify(record));
					getFileMd5('_doc/' + pathUrl + 'audio/' + entry.name, os + entry.name);
					createItem(entry);
				}, function(e) {
					outLine('读取录音文件错误：' + e.message);
				});
			}, function(e) {
				outLine('录音失败：' + e.message);
			});
			er.style.display = 'block';
			t = 0;
			ri = setInterval(function() {
				t++;
				rt.innerText = timeToStr(t);
			}, 1000);
		}
		// 停止录音
		function stopRecord() {
			er.style.display = 'none';
			rt.innerText = '00:00:00';
			clearInterval(ri);
			ri = null;
			r.stop();
			w = null;
			r = null;
			t = 0;
		}
		// 清除历史记录
		function cleanHistory() {
			hl.innerHTML = '<li id="empty" class="ditem-empty">无历史记录</li>';
			le = document.getElementById('empty');
			// 删除音频文件
			outSet('清空录音历史记录：');
			gentry.removeRecursively(function() {
				// Success
				outLine('操作成功！');
			}, function(e) {
				ouline('操作失败：' + e.message);
			});
		}
		// 获取录音历史列表
		function updateHistory() {
			if(bUpdated || !gentry || !document.body) { //兼容可能提前注入导致DOM未解析完更新的问题
				return;
			}
			var reader = gentry.createReader();
			reader.readEntries(function(entries) {
				for(var i in entries) {
					if(entries[i].isFile) {
						createItem(entries[i]);
					}
				}
			}, function(e) {
				outLine('读取录音列表失败：' + e.message);
			});
			bUpdated = true;
		}
		// 获取录音文件信息
		function updateInformation(li) {
			if(!li || !li.entry) {
				return;
			}
			var entry = li.entry;
			entry.getMetadata(function(metadata) {
				li.querySelector('.ainf').innerText = dateToStr(metadata.modificationTime);
			}, function(e) {
				outLine('获取文件"' + entry.name + '"信息失败：' + e.message);
			});
		}
		// 播放音频文件
		function playAudio(li) {
			if(!li || !li.entry) {
				ouSet('无效的音频文件');
				return;
			}

			outSet('播放音频文件：' + li.entry.name);
			startPlay('_doc/' + pathUrl + 'audio/' + li.entry.name);
		}
		// 播放文件相关对象
		var p = null,
			pt = null,
			pp = null,
			ps = null,
			pi = null;
		// 开始播放
		function startPlay(url) {
			ep.style.display = 'block';
			var L = pp.clientWidth;
			p = plus.audio.createPlayer(url);
			p.play(function() {
				outLine('播放完成！');
				// 播放完成
				pt.innerText = timeToStr(d) + '/' + timeToStr(d);
				ps.style.webkitTransition = 'all 0.3s linear';
				ps.style.width = L + 'px';
				stopPlay();
			}, function(e) {
				outLine('播放音频文件"' + url + '"失败：' + e.message);
			});
			// 获取总时长
			var d = p.getDuration();
			if(!d) {
				pt.innerText = '00:00:00/' + timeToStr(d);
			}
			pi = setInterval(function() {
				if(!d) { // 兼容无法及时获取总时长的情况
					d = p.getDuration();
				}
				var c = p.getPosition();
				if(!c) { // 兼容无法及时获取当前播放位置的情况
					return;
				}
				pt.innerText = timeToStr(c) + '/' + timeToStr(d);
				var pct = Math.round(L * c / d);
				if(pct < 8) {
					pct = 8;
				}
				ps.style.width = pct + 'px';
			}, 1000);
		}
		// 停止播放
		function stopPlay() {
			clearInterval(pi);
			pi = null;
			setTimeout(resetPlay, 500);
			// 操作播放对象
			if(p) {
				p.stop();
				p = null;
			}
		}
		// 重置播放页面内容
		function resetPlay() {
			ep.style.display = 'none';
			ps.style.width = '8px';
			ps.style.webkitTransition = 'all 1s linear';
			pt.innerText = '00:00:00/00:00:00';
		}
		// 重写关闭
		var _back = window.back;

		function resetback() {
			// 停止播放
			if(ep.style.display == 'block') {
				stopPlay();
			} else if(er.style.display == 'block') {
				stopRecord();
			} else {
				_back();
			}
		}
		window.back = resetback;
	</script>

</html>